/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.shop.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.shop.entity.Shop;
import com.jeeplus.modules.shop.mapper.ShopMapper;
import com.jeeplus.modules.shopbill.entity.ShopBill;
import com.jeeplus.modules.shopbill.mapper.ShopBillMapper;

/**
 * 实体商家Service
 * @author lixinapp
 * @version 2019-10-16
 */
@Service
@Transactional(readOnly = true)
public class ShopService extends CrudService<ShopMapper, Shop> {
	@Autowired
	private ShopBillMapper shopBillMapper;
	
	public Shop get(String id) {
		return super.get(id);
	}
	
	public List<Shop> findList(Shop shop) {
		return super.findList(shop);
	}
	
	public Page<Shop> findPage(Page<Shop> page, Shop shop) {
		return super.findPage(page, shop);
	}
	
	@Transactional(readOnly = false)
	public void save(Shop shop) {
		super.save(shop);
	}
	
	@Transactional(readOnly = false)
	public void delete(Shop shop) {
		super.delete(shop);
	}

	@Transactional(readOnly = false)
	public void pay(Shop shop) {
		super.save(shop);
		// 其他逻辑处理
		
	}

	/**
	 * 改余额
	 * @param shop 商家
	 * @param title 标题
	 * @param amount 金额
	 * @param type 0支出 1收入
	 * @param orderId 订单号
	 * @param content 描述
	 * @param username 收货人
	 * @param phone 电话
	 */
	@Transactional(readOnly = false)
	public synchronized void updateBalance(Shop shop, String title, String amount, String type, String orderId, String content, String username, String phone, Date finishDate) {
		// 添加账单记录
		ShopBill shopBill = new ShopBill();
		shopBill.preInsert();
		shopBill.setShop(shop);
		shopBill.setTitle(title);
		shopBill.setAmount(amount);
		shopBill.setType(type);
		shopBill.setOrderId(orderId);
		shopBill.setContent(content);
		shopBill.setQty(1);
		shopBill.setUsername(username);
		shopBill.setPhone(phone);
		shopBill.setFinishDate(finishDate);
		shopBillMapper.insert(shopBill);
		
		// 修改余额
		if ("0".equals(type)) {
			mapper.execUpdateSql("UPDATE t_shop SET balance = balance - "+amount+" WHERE id = '"+shop.getId()+"'");
		} else {
			mapper.execUpdateSql("UPDATE t_shop SET balance = balance + "+amount+" WHERE id = '"+shop.getId()+"'");
		}
	}

	public List<Map<String, Object>> shopOption(String shopId, String beginDate, String endDate) {
		return mapper.shopOption(shopId, beginDate, endDate);
	}
	
}